package com.bw.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.bw.domain.Menu;
import com.bw.service.MenuService;

import java.util.List;


public class CellDataDemoHeadDataListener implements ReadListener<Menu> {

    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<Menu> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private MenuService menuService;

    public CellDataDemoHeadDataListener(MenuService menuService) {
        this.menuService = menuService;
    }
    @Override
    public void invoke(Menu data, AnalysisContext analysisContext) {
         //menuService.insertUsers(  date);
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            menuService.insertMenus(cachedDataList);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        menuService.insertMenus(cachedDataList);
        System.out.println("--------解析完之后的方法----------");
    }
}
